package com.hemh.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hemh.entity.OmsUser;
import com.hemh.service.UserService;
import com.hemh.utils.AESUtil;
import com.hemh.utils.ResponseUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@Api(value="User相关操作的接口")
public class UserController {

	private final Log logger = LogFactory.getLog(UserController.class);
	
	@Resource
	private UserService userService;

	@PostMapping("/user/login")
	@ApiOperation(value="用户登录接口")
	@ResponseBody
    public Object userLogin(@RequestParam String usernumber,
            @RequestParam String password){
		Map<String, String> result = new HashMap<String, String>();		
		try {
			result = userService.userLogin(usernumber, password);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtil.fail();
		}	
		logger.info("--->>>登录结果 : " + result);
        return result;
    }
	
	@PostMapping("/user/register")
	@ApiOperation(value="用户注册接口")
	@ResponseBody
    public Object userRegister(@RequestParam String username,
            @RequestParam String usernumber,
            @RequestParam String password,
            @RequestParam String sex,
            @RequestParam String email,
            @RequestParam boolean isAdmin){
		int result = 0;
		/** 封装 */
		OmsUser user = new OmsUser();
		user.setUserName(username);
		user.setUserNumber(usernumber);
		try {
			user.setPassword(AESUtil.encrypt(password));
		} catch (Exception e) {
			logger.error("--->>>AES编码异常 : " + e);
		}
		user.setSex(sex);
		user.setEmail(email);
		user.setIsAdmin(isAdmin);
		result = userService.userRegister(user);
		logger.info("--->>>注册结果 : " + result);
        return result;
    }
	
	@PostMapping("/user/updatePassword")
	@ApiOperation(value="用户密码修改接口")
	@ResponseBody
    public Object userUpdatePassword(@RequestParam String usernumber,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {
		String result = "" ;
		try {
			result = userService.updateUserPassword(usernumber, oldPassword, newPassword);
			logger.info("--->>>密码修改结果 : " + result);
			return ResponseUtil.ok(result);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtil.fail();
		}		
	}
	
}
